package main

import (
	"context"
	"fmt"
	"golang.org/x/sync/errgroup"
	"io"
	"net/http"
	"os"
	"os/signal"
)
func HelloServer(w http.ResponseWriter,rqe *http.Request){
	io.WriteString(w,"welcome")
}

func startHttpServer(ser *http.Server) error{
	http.HandleFunc("/hello", HelloServer)
	fmt.Println("http server start")
	err := ser.ListenAndServe()
	return err
}



func main(){
	ctx, cancel := context.WithCancel(context.Background())

	group ,errCtx := errgroup.WithContext(ctx)
	ser := &http.Server{
		Addr:              "127.0.0.1:8000",
		Handler:           nil,
		TLSConfig:         nil,
		ReadTimeout:       0,
		ReadHeaderTimeout: 0,
		WriteTimeout:      0,
		IdleTimeout:       0,
		MaxHeaderBytes:    0,
		TLSNextProto:      nil,
		ConnState:         nil,
		ErrorLog:          nil,
		BaseContext:       nil,
		ConnContext:       nil,
	}
	group.Go(func() error {
		return startHttpServer(ser)
	})
	group.Go(func() error {
		<- errCtx.Done()
		fmt.Println("http server stop")
		return ser.Shutdown(errCtx)
	})
	c := make(chan os.Signal, 1)
	signal.Notify(c)

	group.Go(func() error {
		for {
			select {
			case <- errCtx.Done():
				return errCtx.Err()
			case <- c:
				cancel()
			}
		}
		return nil

	})
	if err:=group.Wait();err!=nil{
		fmt.Println("group error:", err)
	}
	fmt.Println("all done!")
}